const express = require("express");
const router = express.Router();

const cartModule=require('../database/module/cartModule');
const MVOModule=require('../database/module/MVOModule');
const BVOModule=require('../database/module/bvoModule');
const orderModule=require('../database/module/orderModule');
const productModule=require('../database/module/productModule');
const balanceRecordModule = require('../database/module/balanceRecordModule');
const bvoModule = require('../database/module/bvoModule');
const userInfoModule = require('../database/module/userInfoModule');

//(提交)生成订单
router.all("/submitOrder", (req, res) => {
  const data = req.body;
  productModule.findOne({ _id: data.product_id }).then((result) => {
    const date = new Date();
    const order = {
      order_id: "oid" + Date.parse(date.toUTCString()),
      product_id: data.product_id,
      bvo_id: data.bvo_id,
      mvo_id: result.mvo_id,
      amount: data.amount,
      time: date,
      status: 0,
    };
    orderModule
      .create(order)
      .then((order_data) => {
        res.send(true);
      })
      .catch(() => {
        res.send(false);
      });
  });
});

//return [{order_id, name, price, amount, image_url, status, time}]
async function getProductDetail(result, ret) {
  let i;
  for (i = 0; i < result.length; i++) {
    let e = result[i];
    await productModule.findOne({ _id: e.product_id }).then((product) => {
      const obj = {
        order_id: e.order_id,
        name: product.name,
        price: product.price,
        amount: e.amount,
        image_url: product.image_url,
        status: e.status,
        time: e.time,
      };
      ret.push(obj);
    });
  }
}
//查看所有订单
router.all("/findAllOrders", (req, res) => {
  let ret = [];
  orderModule.find().then((result) => {
    getProductDetail(result, ret).then(() => {
      res.send(ret);
    });
  });
});
//查看指定品牌商的所有订单
router.all("/findAllMVOOrder", (req, res) => {
  let ret = [];
  const data = req.body;
  orderModule
    .find({ mvo_id: data.mvo_id })
    .then((result) => {
      getProductDetail(result, ret).then(() => {
        res.send(ret);
      });
    })
    .catch((err) => {
      console(err);
    });
});
//查看指定借卖方的所有订单
router.all("/findAllBVOOrder", (req, res) => {
  let ret = [];
  const data = req.body;
  orderModule
    .find({ bvo_id: data.bvo_id })
    .then((result) => {
      getProductDetail(result, ret).then(() => {
        res.send(ret);
      });
    })
    .catch((err) => {
      console.log(err);
    });
});
//订单发货
router.all("/startOrder", (req, res) => {
  const data = req.body;
  orderModule
    .updateOne({ order_id: data.order_id }, { status: 1 })
    .then(() => {
      res.send(true);
    })
    .catch((err) => {
      res.send(false);
    });
});

//完成订单
router.all("/finishOrder", (req, res) => {
  const data = req.body;
  let temp;
  let price;
  let amount;
  console.log(new Date());
  orderModule
    .updateOne({ order_id: data.order_id }, { status: 2 })
    .then((result) => {
      res.send(true);

      orderModule.findOne({ order_id: data.order_id }).then((result) => {
        productModule.findOne({ _id: result.product_id }).then((pro) => {
          price = pro.price;
          amount = result.amount;
          temp = price * amount;

          console.log("temp", temp, price, amount);
          BVOModule.findOne({ bvo_id: result.bvo_id }).then((bvo) => {
            console.log(bvo.user_id);
            balanceRecordModule 
              .findOne({ user_id: bvo.user_id })
              .sort({ time: -1 })
              .then((bal_bvo) => {
                console.log('bbb',bal_bvo);
                let bvo_bal = bal_bvo.balance - temp;
                console.log("bvo", bal_bvo.balance, bvo_bal);
                /*balanceRecordModule.updateOne({user_id:bvo.user_id},{old_balance:bal_bvo.balance,balance:bvo_bal}).then(()=>{
                    userInfoModule.updateOne({user_id:bvo.user_id},{balance:bvo_bal}).then(()=>{

                                    })
                 });*/
                balance = {
                  user_id: bvo.user_id,
                  old_balance: bal_bvo.balance,
                  balance: bvo_bal,
                  time: new Date(),
                };
                balanceRecordModule.create(balance);
                userInfoModule.updateOne(
                  { user_id: bvo.user_id },
                  { $set:{ balance: bvo_bal }}
                ).then();
              });
          });
          MVOModule.findOne({ mvo_id: result.mvo_id }).then((mvo) => {
            console.log(mvo.user_id);
            balanceRecordModule
              .findOne({ user_id: mvo.user_id })
              .sort({ time: -1 })
              .then((bal_mvo) => {
                let mvo_bal = bal_mvo.balance + temp;
                console.log("mvo", bal_mvo.balance, mvo_bal);
                /* balanceRecordModule.updateOne({user_id:mvo.user_id},{old_balance:bal_mvo.balance,balance:mvo_bal}).then(()=>{
                        userInfoModule.updateOne({user_id:mvo.user_id},{balance:mvo_bal}).then(()=>{
                                            
                                        })
                 });*/
                balance = {
                  user_id: mvo.user_id,
                  old_balance: bal_mvo.balance,
                  balance: mvo_bal,
                  time: new Date(),
                };
                balanceRecordModule.create(balance);

                userInfoModule.findOneAndUpdate(
                  { user_id: mvo.user_id },
                  { $set:{ balance: mvo_bal }}
                ).then();
              });
          });
        });
      });
    })
    .catch((err) => {
      res.send(false);
    });
});

//取消订单
router.all("/cancelOrder", (req, res) => {
  const data = req.body;
  orderModule
    .updateOne({ order_id: data.order_id }, { status: 3 })
    .then(() => {
      res.send(true);
    })
    .catch((err) => {
      res.send(false);
    });
});

module.exports = router;
